﻿using System;
using System.Linq;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using System.Collections.Generic;
using Foxit.PDF.Merger;
using System.Diagnostics;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.PdfGeneration.Service;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Threading.Tasks;
using Sustainalytics.Entities;
using Sustainalytics.ESG.Entities;

namespace Sustainalytics.ReportGenerator.BL.Tests
{
    [TestClass]
    public class PdfReportRendererTest
    {
        [TestMethod]
        public void ControversiesSectionTest()
        {
            var companyReportDataOffline = GetCompanyReportDataOffline();

            var controversiesSection = new ControversiesSection();
            controversiesSection.ShowOutlines = true;

            var result = controversiesSection.GeneratePdfDocument(companyReportDataOffline);

            SavePdfReport(result.PdfDocument, "ControversiesSection");

            var pdfDocument = new PdfDocument(result.PdfDocument);
            var firstPageText = pdfDocument.GetPage(1).GetText();

            const string expectedText = "Environment Controversies";

            Assert.IsNotNull(result.PdfDocument, "The expected pdf document is null!");
            Assert.IsTrue(firstPageText.Contains(expectedText), "First page does not contain expected text!");
        }

        [TestMethod]
        public void ControversyReportSectionTest()
        {
            var companyReportDataOffline = GetCompanyReportDataOffline();

            companyReportDataOffline.CorporateData.HeadquarterLatitude = 51.4047021;
            companyReportDataOffline.CorporateData.HeadquarterLongitude = 5.4168205;

            var controversyReportSections = new ControversyReportSections();

            var result = controversyReportSections.GeneratePdfDocument(companyReportDataOffline);

            SavePdfReport(result.PdfDocument, "ControversyReportSections");

            var pdfDocument = new PdfDocument(result.PdfDocument);
            var firstPageText = pdfDocument.GetPage(1).GetText();
        }

        [TestMethod]
        public void GetPdfReportTest()
        {
            var sw = Stopwatch.StartNew();

            var crdo = GetCompanyReportDataOffline();

            crdo.ReportType = ReportType.ComprehensiveReport;

            var clientReportPdfRenderer = new PdfReportRenderer(crdo, true, false);

            var result = clientReportPdfRenderer.GetPdfDocument();

            SavePdfReport(result[0], crdo.ReportType.ToString());


            sw.Stop();
        }


        [TestMethod]
        public void Bug3698Test()
        {


            var exchangeCode = string.Empty;
            var ticker = string.Empty;
            {
                var crdo = GetCompanyReportDataOffline();


                crdo.ReportType = ReportType.ComprehensiveReport;

                var clientReportPdfRenderer = new PdfReportRenderer(crdo, false, false);

                var result = clientReportPdfRenderer.GetPdfDocument();

                SavePdfReport(result[0], crdo.ReportType.ToString());

                var pdfDocument = new PdfDocument(result[0]);
                var firstPageText = pdfDocument.GetPage(1).GetText();


                Assert.IsNotNull(result, "The expected pdf document is null!");
                Assert.IsTrue(firstPageText.Contains("Ticker: " + crdo.CorporateData.MainExchange + ":" + crdo.CorporateData.MainTicker), "First page does not contain expected text!");

            }

            {

                var crdo = GetCompanyReportDataOffline();


                crdo.ReportType = ReportType.ComprehensiveReport;
                exchangeCode = crdo.CorporateData.MainExchange;
                ticker = crdo.CorporateData.MainTicker;
                crdo.CorporateData.MainExchange = null;
                crdo.CorporateData.MainTicker = null;
                var clientReportPdfRenderer = new PdfReportRenderer(crdo, false, false);

                var result = clientReportPdfRenderer.GetPdfDocument();


                SavePdfReport(result[0], crdo.ReportType + "2");


                crdo.CorporateData.MainExchange = exchangeCode;
                crdo.CorporateData.MainTicker = ticker;

                var pdfDocument = new PdfDocument(result[0]);
                var firstPageText = pdfDocument.GetPage(1).GetText();


                Assert.IsNotNull(result, "The expected pdf document is null!");
                Assert.IsTrue(!firstPageText.Contains("Ticker: " + crdo.CorporateData.MainExchange + ":" + crdo.CorporateData.MainTicker)

                    && firstPageText.Contains("Ticker:")
                    , "First page does not contain expected text!");
            }


        }

        [TestInitialize]
        public void Initialize()
        {
            SetupFakeData();
        }

        #region Data

        private Analyst _analyst;
        private CorporateData _corporateData;
        private List<EventIndicator> _eventIndicators;
        private FinancialData _financialData;
        private List<Incident> _incidents;
        private List<RPIndicatorExtended> _indicatorsPerformance;
        private List<IndicatorTemplate> _indicatorTemplates;
        private List<CompanyScore> _industryPeers;
        private List<CompanyScore> _industryTopPerformers;
        private List<KeyEsgIssue> _keyEsgIssues;
        private OverallPerformance _overallPerformance;

        private List<SubPeerGroupKeyEsgIssue> _subPeerGroupKeyEsgIssues;
        private List<ThemePerformance> _themesPerformance;
        private static T Deserialize<T>(string json)
        {
            var serializer = new JsonSerializer();
            var streamReader = new StreamReader(json);
            var textReader = new JsonTextReader(streamReader);
            return serializer.Deserialize<T>(textReader);
        }

        private static List<CompanyHistoryData> FakeCompanyHistoryData()
        {
            var companyHistoricalPerformance = new List<CompanyHistoryData>();

            var currentDate = DateTime.UtcNow.Date;
            var date = new DateTime(currentDate.Year, currentDate.Month, 1);

            for (var month = 1; month <= 36; month++)
            {
                var historyDate = date.AddMonths(-1 * month);

                var companyHistoryData = new CompanyHistoryData
                {
                    Date = historyDate,
                    OverallBestInClass = 80,
                    OverallAverage = 60,
                    OverallScore = 40,
                    EnvironmentBestInClass = 80,
                    EnvironmentAverage = 60,
                    EnvironmentScore = 40,
                    SocialBestInClass = 80,
                    SocialAverage = 60,
                    SocialScore = 40,
                    GovernanceBestInClass = 80,
                    GovernanceAverage = 60,
                    GovernanceScore = 40
                };

                companyHistoricalPerformance.Add(companyHistoryData);
            }
            return companyHistoricalPerformance;
        }

        private static void LoadControversyIndicators(CompanyReportDataOffline crdo)
        {
            var controversyIndicators = crdo.EventIndicators.Where(ei => ei.ProvidesControversy)
                .Select(ei => new RPControversyIndicator
                {
                    Id = Guid.NewGuid(),
                    CompanyId = ei.CompanyId,
                    Template = crdo.IndicatorTemplates.SingleOrDefault(it => it.Id == ei.ControversyIndicatorId),
                    AnswerCategory = ei.AnswerCategory,
                    AnswerCategoryScore = ei.AnswerCategoryScore,
                    AnswerCategoryText = ei.AnswerCategoryText,
                    OutlookScore = ei.OutlookScore
                }).ToList();

            controversyIndicators.ForEach(ci =>
            {
                ci.EventIndicators = crdo.EventIndicators.Where(ei => ei.ControversyIndicatorId == ci.Template.Id
                    && ei.AnswerCategory > 0)
                    .Select(ei => new EventIndicatorSummary
                    {
                        Id = ei.BaseEventIndicatorId,
                        Name = ei.Name

                    }).ToList();
            });

            crdo.ControversyIndicators = controversyIndicators;


            var controversies = controversyIndicators
                .GroupBy(ci => new { ci.AnswerCategory, ci.Template.Number })
                .Select(group => new
                {
                    Category = group.Key.AnswerCategory,
                    Count = group.Count(),
                    ControversyIndicatorNumber = group.Key.Number
                })
                .ToList();

            var random = new Random();

            var comparisonGroupControversies = new List<ComparisonGroupControversy>();

            foreach (var controversyIndicator in controversyIndicators)
            {
                for (var ctg = 0; ctg <= 5; ctg++)
                {
                    var percent = random.Next(0, 100);

                    comparisonGroupControversies.Add(new ComparisonGroupControversy
                    {
                        ControversyIndicatorNumber = controversyIndicator.Template.Number,
                        Category = ctg,
                        Percent = percent
                    });
                }
            }

            crdo.ComparisonGroupControversies = comparisonGroupControversies;
        }

        private static void LoadMarketCapitalization(CompanyReportDataOffline crdo)
        {
            double min = 0;
            double max = 0;

            if (crdo.IndustryPeers != null && crdo.IndustryPeers.Any())
            {
                var minMarkerCap = crdo.IndustryPeers.Min(p => p.MarketCapitalization);
                var maxMarkerCap = crdo.IndustryPeers.Max(p => p.MarketCapitalization);

                if (minMarkerCap > 0)
                    min = minMarkerCap / 1000;

                if (maxMarkerCap > 0)
                    max = maxMarkerCap / 1000;
            }

            crdo.IndustryPeersMinCapitalization = min;
            crdo.IndustryPeersMaxCapitalization = max;
        }

        private static void SavePdfReport(byte[] file, string fileName)
        {
            if (!Directory.Exists(@"E:\Reports\"))
                Directory.CreateDirectory(@"E:\Reports\");

            System.IO.File.WriteAllBytes(Path.Combine(@"E:\Reports\", fileName + ".pdf"), file);
        }

        private CompanyReportDataOffline GetCompanyReportDataOffline()
        {


            var companyReportDataOffline = new CompanyReportDataOffline
            {
                ReportType = ReportType.ComprehensiveReport,
                CompanyId = _corporateData.Id,
                ESGProfile = ESGProfile.DefaultProfile,

                CorporateData = _corporateData,
                FinancialData = _financialData,
                //ReferenceData = _referenceData,
                OverallPerformance = _overallPerformance,
                IndustryTopPerformers = _industryTopPerformers,
                IndustryPeers = _industryPeers,
                CompanyHistoricalPerformance = FakeCompanyHistoryData(),
                Analyst = _analyst,
                SubPeerGroupKeyEsgIssues = _subPeerGroupKeyEsgIssues,
                KeyEsgIssues = _keyEsgIssues,
                IndicatorTemplates = _indicatorTemplates,
                ThemesPerformance = _themesPerformance,
                StandardIndicators = _indicatorsPerformance,
                EventIndicators = _eventIndicators,
                Incidents = _incidents,
                Sources = new List<Source>()
            };

            companyReportDataOffline.ESGProfile.CompanyType = CompanyTypeEnum.Private;
            companyReportDataOffline.ESGProfile.TemplateType = TemplateTypeEnum.TypeB;


            LoadMarketCapitalization(companyReportDataOffline);
            LoadControversyIndicators(companyReportDataOffline);

            return companyReportDataOffline;
        }

        private void SetupFakeData()
        {
            _corporateData = new CorporateData
            {
                Id = new Guid("020ecd44-3227-449b-a80f-c74fada65c83"),
                CompanyName = "Vedanta Resources plc",
                CompanyType = "Public",
                TemplateType = "Type A",
                Country = "United Kingdom",
                Region = "Region",
                PeerGroup = "Diversified Metals",
                SustainalyticsIndustry = "Industry",
                SustainalyticsIndustryGroup = "Industry Group",
                SustainalyticsSector = "Sector",
                SustainalyticsSubIndustry = "Sub Industry",
                CapitalIqId = 123456789,
                TotalEmployees = 86479,
                MainExchange = "LSE",
                MainTicker = "VED",
                SubPeerGroup = "Peer Group And Sub Industry"
            };

            _financialData = new FinancialData
            {
                Id = new Guid("00000001-0000-0000-0000-000000000000"),
                MarketCapitalization = null
            };

            _analyst = new Analyst
            {
                FirstName = "Irene",
                LastName = "Sosa",
                Email = "irene.sosa@sustainalytics.com",
                Picture = ImagesGenerator.GetJpgImage(@"Images\research_product_manager.png")
            };

            _overallPerformance = new OverallPerformance
            {
                CompanyScore = 55,
                CompanyRank = -1, //41,
                CompanyCount = 70,
                Percentile = 0, //2,
                EnvironmentScore = 49,
                SocialScore = 48,
                GovernanceScore = 75,
                CompanyAssessment = new RPAssessment { Id = 3, Name = "Average Performer" },
                EnvironmentAssessment = new RPAssessment { Id = 3, Name = "Average Performer" },
                SocialAssessment = new RPAssessment { Id = 3, Name = "Average Performer" },
                GovernanceAssessment = new RPAssessment { Id = 3, Name = "Average Performer" },
                IsInReferenceUniverse = false
            };

            _industryTopPerformers = new List<CompanyScore>
            {
                new CompanyScore
                {
                    CompanyId = _corporateData.Id,
                    CompanyName = _corporateData.CompanyName,
                    Score = _overallPerformance.CompanyScore,
                    Rank = 5
                }
            };

            _industryPeers = new List<CompanyScore>
            {
                new CompanyScore
                {
                    CompanyId = _corporateData.Id,
                    CompanyName = _corporateData.CompanyName,
                    Score = _overallPerformance.CompanyScore,
                    Rank = -1,
                    MarketCapitalization = 89000
                }
            };

            _themesPerformance = new List<ThemePerformance>
            {
                new ThemePerformance
                {
                    ThemeName = "Environment",
                    Weight = 0.35f,
                    Score = 49,
                    Assessment = "Average Performer",
                    Rank = 1,
                    Count = 1,
                    Percentile = 0,
                    IsInReferenceUniverse = false
                },
                new ThemePerformance
                {
                    ThemeName = "Social",
                    Weight = 0.4f,
                    Score = 48,
                    Assessment = "Average Performer",
                    Rank = 56,
                    Count = 70,
                    Percentile = 20,
                    IsInReferenceUniverse = false
                },
                new ThemePerformance
                {
                    ThemeName = "Governance",
                    Weight = 0.25f,
                    Score = 75,
                    Assessment = "Average Performer",
                    Rank = 16,
                    Count = 70,
                    Percentile = 78,
                    IsInReferenceUniverse = false
                }
            };

            _subPeerGroupKeyEsgIssues = new List<SubPeerGroupKeyEsgIssue>
            {
                new SubPeerGroupKeyEsgIssue
                {
                    Name = "Human Rights",
                    Description = "Human Rights focuses on how companies manage the respect human rights within their sphere of influence. Particular focus is put on measures taken to protect civil and political rights as well economic, social and cultural rights as enshrined in the UN Universal Declaration of Human Rights including its covenants.  Labour rights and civil rights and political rights related to the use of private data are covered under different ESG issues.",
                    SortKey = 1,
                    SustainabilityImpact = 3,
                    BussinessImpact = 3
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 2,
                    Name = "Land Use & Biodiversity",
                    Description = "Biodiversity focuses on how companies manage biodiversity, including land use and the impact of the company's operations on ecosystems and wildlife. Topics covered include land conversion, forest management as well as protection of biodiversity and ecosystems. Depending on the industry, the focus can be on land use, biodiversity or both.",
                    SustainabilityImpact = 5,
                    BussinessImpact = 7
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 3,
                    Name = "Human Capital",
                    Description = "Human Capital focuses on the management of labour relations and/or the management of business risks as a result of demographic changes notably skills shortages. Depending on the industry, the emphasis can be more on the former (e.g. retailing) or the latter (e.g. machinery) or both. It also includes the management of core labour rights such as freedom of association and non-discrimination.",
                    SustainabilityImpact = 6,
                    BussinessImpact = 6
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 4,
                    Name = "Water Use",
                    Description = "Water Use focuses on the management of water use and reporting of risks related to water scarcity through the company's operations or its supply chain. Depending on the industry, the emphasis is put on the former, the latter or both dimensions. The issue focuses on the use of water as a raw material, not on the treatment and management of process water, which is covered under Emissions, Releases and Waste.",
                    SustainabilityImpact = 1,
                    BussinessImpact = 2
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 5,
                    Name = "Physical Climate Change Risks",
                    Description = "Physical Climate Change Risks focuses on how companies manage physical risks posed by climate change, i.e.  higher frequencies of extreme weather events including draughts, flooding, storms, heat waves etc. The emphasis is put on companies' approach to risk assessment and risk management to protect corporate assets from such risks.",
                    SustainabilityImpact = 1,
                    BussinessImpact = 2
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 6,
                    Description = "Emissions Effluents and Waste focuses on the management of emissions and releases from operations to air, water and land excluding GHG emissions. Depending on the industry, the emphasis is put on one or several of these three 'waste streams'. Management of shipwrecking is also covered under this ESG issue as well as nuclear waste.",
                    Name = "Emissions, Effluents & Waste",
                    SustainabilityImpact = 9,
                    BussinessImpact = 7
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 7,
                    Name = "Bribery & Corruption",
                    Description = "Bribery and corruption focuses on the management of risks related to the potential illegal payments, such as kickbacks, bribes and facilitation payments to government officers, as well as the receipt of those payments from suppliers or business partners. In the extractive industry, the issue also covers adoption of relevant transparency standards with regards to payments to host governments in the form of taxes and royalties.",
                    SustainabilityImpact = 1,
                    BussinessImpact = 2
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 8,
                    Name = "Health and Safety",
                    Description = "Health and Safety focuses on the management of health and safety amongst employees and contractors. Depending on the industry and where relevant, topics also include HIV/Aids programmes.",
                    SustainabilityImpact = 9,
                    BussinessImpact = 8
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 9,
                    Name = "Community Relations",
                    Description = "Community Relations focuses on how companies manage relations with local communities (including indigenous communities). Local communities typically comprise communities in the vicinity of a company's operating sites or communities directly impacted by these. Depending on the industry, the emphasis is put on community involvement, community development and/or measures to reduce negative impacts on local communities.",
                    SustainabilityImpact = 8,
                    BussinessImpact = 8
                },
                new SubPeerGroupKeyEsgIssue
                {
                    SortKey = 10,
                    Name = "Resilience",
                    Description = "Resilience focuses on the financial stability and the management of related risks in the financial services industry. This ESG issue is limited to those financial institutions that pose systemic risks and therefore potential external costs to society in case of bail outs by taxpayers. Topics include capital adequacy, focus on real economy, sources of financing and proximity to clients.",
                    SustainabilityImpact = 8,
                    BussinessImpact = 8
                }
            };

            _keyEsgIssues = new List<KeyEsgIssue>
            {
                new KeyEsgIssue
                {
                    Name = "Community Relations",
                    Description = "Community Relations focuses on how companies manage relations with local communities (including indigenous communities). Local communities typically comprise communities in the vicinity of a company's operating sites or communities directly impacted by these. Depending on the industry, the emphasis is put on community involvement, community development and/or measures to reduce negative impacts on local communities.",
                    Comment = "The company performs poorly overall in this area. Since 2004, Vedanta’s efforts to develop a bauxite deposit in Odisha have faced strong community opposition. Local indigenous communities fear the project will impact their livelihood and culture. NGOs and the OECD National Contact Point accused the company of failing to adequately consult the Dogria Kondh tribe. In 2013, the Indian Supreme Court granted decision-making power to local village councils, the majority of whom voted against the project. While Vedanta has stated that it will not develop the deposit without local support, its ability to obtain such support may be hindered by its weak consultation programmes. Furthermore, should protests against the project escalate, the company risks becoming complicity in human rights violations conducted by State security forces. Bauxite scarcity forced the company to suspend operations at the Lanjigarh refinery between December 2012 and July 2013.",
                    SortKey = 1,
                    SustainabilityImpact = 8,
                    BussinessImpact = 8,
                    KeyEsgIssueIndicators = new List<KeyEsgIssueIndicator>
                    {
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.4.2.2",
                            Name = "Community Involvement Programmes",
                            Score = "50",
                            Average = "44",
                            BestPractice = "93",
                            MaterialBestPracticeGap = 2
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.4.2.9",
                            Name = "Indigenous Rights Policy",
                            Score = "75",
                            Average = "21",
                            BestPractice = "64",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.4.2.11",
                            Name = "Community Development Programmes",
                            Score = "100",
                            Average = "62",
                            BestPractice = "86",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.EventIndicator,
                            Number = "Event:",
                            Name = "Community Relations",
                            Score = "0",
                            Average = "N/A",
                            BestPractice = "N/A",
                            MaterialBestPracticeGap = 100,
                            AnswerCategory = "Category 5"
                        }
                    }
                },
                new KeyEsgIssue
                {
                    Name = "Emissions, Effluents & Waste",
                    Description = "Emissions Effluents and Waste focuses on the management of emissions and releases from operations to air, water and land excluding GHG emissions. Depending on the industry, the emphasis is put on one or several of these three 'waste streams'. Management of shipwrecking is also covered under this ESG issue as well as nuclear waste.",
                    Comment = "The company has relatively strong health and safety management systems, but poor performance, which makes the company’s overall performance inadequate. The company’s lost-time incident rate has decreased in recent years and the majority of its operations are OHSAS 18001 certified. However, Vedanta reported 19 fatalities in FY2013/14 and 67 since FY2011/12. For a workforce of approximately 87,000, this number is considered high by industry standards. Fatalities generate significant stakeholder scrutiny and can result in operational delays as incident investigations take place. Vedanta’s CEO deemed the company’s fatality rate ‘unacceptable’ and has committed to implementing specific measures to address the main causes of deaths."
                    ,//+ "The company has relatively strong health and safety management systems, but poor performance, which makes the company’s overall performance inadequate. The company’s lost-time incident rate has decreased in recent years and the majority of its operations are OHSAS 18001 certified. However, Vedanta reported 19 fatalities in FY2013/14 and 67 since FY2011/12. For a workforce of approximately 87,000, this number is considered high by industry standards. Fatalities generate significant stakeholder scrutiny and can result in operational delays as incident investigations take place. Vedanta’s CEO deemed the company’s fatality rate ‘unacceptable’ and has committed to implementing specific measures to address the main causes of deaths.",
                    SortKey = 2,
                    SustainabilityImpact = 9,
                    BussinessImpact = 7,
                    KeyEsgIssueIndicators = new List<KeyEsgIssueIndicator>
                    {
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.1",
                            Name = "Community Relations",
                            Score = "50",
                            Average = "44",
                            BestPractice = "83",
                            MaterialBestPracticeGap = 2
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.1.1",
                            Name = "Community Involvement Programmes",
                            Score = "100",
                            Average = "79",
                            BestPractice = "100",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.2",
                            Name = "Environmental Management System",
                            Score = "100",
                            Average = "70",
                            BestPractice = "100",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.3",
                            Name = "EMS Certification",
                            Score = "75",
                            Average = "46",
                            BestPractice = "70",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.3.3",
                            Name = "Air Emissions Programmes",
                            Score = "50",
                            Average = "28",
                            BestPractice = "64",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.3.5",
                            Name = "Other Environmental Programmes",
                            Score = "100",
                            Average = "61",
                            BestPractice = "86",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.4",
                            Name = "Environmental Fines & Penalties",
                            Score = "100",
                            Average = "81",
                            BestPractice = "100",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "E.1.2.6.2",
                            Name = "Mineral Waste Management Research Underway",
                            Score = "N/A",
                            Average = "N/A",
                            BestPractice = "N/A",
                            MaterialBestPracticeGap = 1,
                            HidenToClient = true
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.EventIndicator,
                            Number = "Event:",
                            Name = "Emissions, Effluent and Waste",
                            Score = "0",
                            Average = "N/A",
                            BestPractice = "N/A",
                            MaterialBestPracticeGap = 0,
                            AnswerCategory = "Category 3"
                        },
                    }
                },
                new KeyEsgIssue
                {
                    Name = "Health and Safety",
                    Description = "Health and Safety focuses on the management of health and safety amongst employees and contractors. Depending on the industry and where relevant, topics also include HIV/Aids programmes." +
                    " Health and Safety focuses on the management of health and safety amongst employees and contractors. Depending on the industry and where relevant, topics also include HIV/Aids programmes.",
                    Comment = "Vedanta’s copper operations in Zambia have been fined for polluting the Kafue River and its tributaries, and accused of ruining local farmers’ livelihoods by dumping waste rock on their land. The company spent more than USD 15 million on clean up and new technology to address pollution issues at its Zambian operations in 2010, but continued to face criticism from local communities and international NGOs. Similarly, the company’s Tuticorin copper smelter in India has faced several fines and was closed in 2013 as a result of excessive sulphur dioxide emissions, which led to a 22% profit reduction in Q1 FY2013/14. Despite Vedanta’s strong environmental management system (EMS), given these incidents and the lack of targets to specifically reduce air emissions and hazardous waste, Vedanta’s overall management of this key ESG issue is inadequate.",
                    SortKey = 3,
                    SustainabilityImpact = 9,
                    BussinessImpact = 8,
                    KeyEsgIssueIndicators = new List<KeyEsgIssueIndicator>
                    {
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.4.2.2",
                            Name = "Community Involvement Programmes",
                            Score = "50",
                            Average = "44",
                            BestPractice = "93",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.1.6.2",
                            Name = "Health & Safety Programmes Research Underway",
                            Score = "N/A",
                            Average = "N/A",
                            BestPractice = "N/A",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.1.6.3",
                            Name = "HIV/Aids Programmes",
                            Score = "100",
                            Average = "38",
                            BestPractice = "65",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.1.6.5",
                            Name = "LTIR Trend",
                            Score = "100",
                            Average = "59",
                            BestPractice = "100",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.StandardIndicator,
                            Number = "S.1.6.6",
                            Name = "Employee Fatalities",
                            Score = "0",
                            Average = "59",
                            BestPractice = "82",
                            MaterialBestPracticeGap = 1
                        },
                        new KeyEsgIssueIndicator
                        {
                            Type = KeyEsgIssueIndicatorType.EventIndicator,
                            Number = "Event:",
                            Name = "Health and Safety",
                            Score = "50",
                            Average = "N/A",
                            BestPractice = "N/A",
                            MaterialBestPracticeGap = 100,
                            AnswerCategory = "Category 1"
                        }
                    }
                }
            };

            _indicatorsPerformance = Deserialize<List<RPIndicatorExtended>>(@"Data\StandardIndicators.json");
            _indicatorTemplates = Deserialize<List<IndicatorTemplate>>(@"Data\IndicatorTemplates.json");
            _eventIndicators = Deserialize<List<EventIndicator>>(@"Data\EventIndicators.json");
            _incidents = Deserialize<List<Incident>>(@"Data\Incidents.json");
        }

        #endregion
        [TestMethod]
        public void ReportParametersSectionTest()
        {
            var companyReportDataOffline = GetCompanyReportDataOffline();

            var sourcesSection = new ReportParametersSection();

            var result = sourcesSection.GeneratePdfDocument(companyReportDataOffline);

            SavePdfReport(result.PdfDocument, "ReportParametersSection");

            var pdfDocument = new PdfDocument(result.PdfDocument);
            var firstPageText = pdfDocument.GetPage(1).GetText();

            const string expectedText = @"Report";

            Assert.IsNotNull(result.PdfDocument, "The expected pdf document is null!");
            Assert.IsTrue(firstPageText.Contains(expectedText), "First page does not contain expected text!");
        }

        [TestMethod]
        public void SourcesSectionTest()
        {
            var companyReportDataOffline = GetCompanyReportDataOffline();

            var sourcesSection = new SourcesSection();

            var result = sourcesSection.GeneratePdfDocument(companyReportDataOffline);

            SavePdfReport(result.PdfDocument, "SourcesSection");

            var pdfDocument = new PdfDocument(result.PdfDocument);
            var firstPageText = pdfDocument.GetPage(1).GetText();

            const string expectedText = "Sources";

            Assert.IsNotNull(result.PdfDocument, "The expected pdf document is null!");
            Assert.IsTrue(firstPageText.Contains(expectedText), "First page does not contain expected text!");
        }

        [TestMethod]
        public void StandardIndicatorsSectionTest()
        {
            var companyReportDataOffline = GetCompanyReportDataOffline();

            var standardIndicatorsSection = new StandardIndicatorsSection() { ShowOutlines = true };

            var result = standardIndicatorsSection.GeneratePdfDocument(companyReportDataOffline);

            SavePdfReport(result.PdfDocument, "StandardIndicatorsSection");

            var pdfDocument = new PdfDocument(result.PdfDocument);
            var firstPageText = pdfDocument.GetPage(1).GetText();

            Assert.IsNotNull(result.PdfDocument, "The expected pdf document is null!");
        }
    }
}
